package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.CartProductDtoMapper;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.service.ICartService;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Map;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: haiyuny
 * @Date: 2022/7/29 16:03
 * @Description:
 */
@Service
public class ICartServiceImpl implements ICartService {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;


    /**
     * 获得购物车商品列表
     *
     * @param request
     * @return
     */
    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        try {
            request.requestCheck();
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId().toString());
            ArrayList<CartProductDto> cartProductDtos = new ArrayList<>();
            for (Map.Entry<Object, Object> goods : map.entrySet()) {
                CartProductDto goodsValue = (CartProductDto) goods.getValue();
                cartProductDtos.add(goodsValue);
            }
            // 代码执行到这里，业务逻辑执行成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            response.setCartProductDtos(cartProductDtos);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    /**
     * 添加商品到购物车
     *
     * @param request
     * @return
     */
    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
        try {
            request.requestCheck();
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId());
            Long itemId = request.getProductId();
            CartProductDto cartProductDto = (CartProductDto) map.get(itemId);
            //如果购物车内已有该商品
            if (cartProductDto != null) {
                cartProductDto.setProductNum(cartProductDto.getProductNum() + 1);
            } else {
                Item item = itemMapper.selectByPrimaryKey(itemId);
                cartProductDto = CartItemConverter.item2Dto(item);
                cartProductDto.setProductNum(1L);
                cartProductDto.setChecked("false");
            }
            map.put(itemId, cartProductDto);
            // 代码执行到这里，业务逻辑执行成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 更新购物车中商品的数量
     *
     * @param request
     * @return
     */
    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            request.requestCheck();
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId());
            Long itemId = request.getProductId();
            CartProductDto cartProductDto = (CartProductDto) map.get(itemId);
            cartProductDto.setProductNum(((long) request.getProductNum()));
            cartProductDto.setChecked(request.getChecked());
            map.put(itemId, cartProductDto);

            // 代码执行到这里，业务逻辑执行成功
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            //response.setCartProductDtos();
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            request.requestCheck();

            List<CartProductDto> list = new LinkedList<>();
            RMap<Long, CartProductDto> map = redissonClient.getMap(String.valueOf(request.getUserId()));
            for (Long aLong : map.keySet()) {
                CartProductDto cartProductDto = map.get(aLong);
                if (cartProductDto.getChecked() != request.getChecked()) {
                    cartProductDto.setChecked(request.getChecked());
                    list.add(cartProductDto);

                }
            }
            for (CartProductDto cartProductDto : list) {
                map.replace(cartProductDto.getProductId(), cartProductDto);
            }

            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {

        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            request.requestCheck();

            RMap<Long, CartProductDto> map = redissonClient.getMap(String.valueOf(request.getUserId()));
            map.remove(request.getItemId());

            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }


        return response;

    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {

        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        try {
            request.requestCheck();

            List<Long> list = new LinkedList<>();
            RMap<Long, CartProductDto> map = redissonClient.getMap(String.valueOf(request.getUserId()));
            for (Long aLong : map.keySet()) {
                CartProductDto cartProductDto = map.get(aLong);
                if ("true".equals(cartProductDto.getChecked())) {
                    list.add(aLong);
                }
            }
            for (Long aLong : list) {
                map.remove(aLong);
            }

            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    /**
     * 下单后清空购物车
     *
     * @author: 叶熠彬
     * @date: 2022/8/1 9:26
     * @param: [request]
     * @return: com.cskaoyan.mall.dto.ClearCartItemResponse
     */
    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse response = new ClearCartItemResponse();
        try {
            request.requestCheck();
            RMap<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
            List<Long> productIds = request.getProductIds();
            for (Long aLong : map.keySet()) {
                if (productIds.contains(aLong)) {
                    map.remove(aLong);
                }
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return null;
    }
}
